package com.xmh.ssm.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Date;

import org.apache.log4j.Logger;

public class FileUtil {

	private final static Logger logger = Logger.getLogger(FileUtil.class);

	public static void outFile(Date date, String path) {
		try {
			String dateToString = DateUtil.getDateToString(date);

			File file = new File(path);

			if (!file.exists()) {
				file.createNewFile();
			}
			PrintWriter out = new PrintWriter(new FileWriter(file));

			out.write(dateToString);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error(e);
		}
	}

	public static void outFile(String data, String path) {
		try {
			File file = new File(path);

			if (!file.exists()) {
				file.createNewFile();
			}
			PrintWriter out = new PrintWriter(new FileWriter(file));

			out.write(data);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error(e);
		}
	}

	public static boolean isExist(String path) {
		File file = new File(path);
		return file.exists();
	}

	public static Date getFile(String path) {
		return DateUtil.getStringToDate(getFileStr(path));
	}

	public static String getFileStr(String path) {
		File file = new File(path);

		Reader in = null;

		String string = null;
		FileInputStream in2 = null;
		try {
			in2 = new FileInputStream(file);
			in = new InputStreamReader(in2, "utf-8");
			StringBuffer sBuffer = new StringBuffer();

			int len = -1;
			while ((len = in.read()) != -1) {
				sBuffer.append((char) len);
			}
			in.close();
			string = sBuffer.toString();
		} catch (IOException e) {
			logger.error(e);
			return null;
		} finally {
			try {
				if (in2 != null) {
					in2.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				logger.error(e);
				return null;
			}
		}
		return string;
	}
}
